<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\User;
use app\model\Note;
use app\model\NoteDraw;
use app\model\NoteDrawItem;
use app\model\CommissionRecord;
use app\util\QrCode;
use EasyWeChat\Factory;
use think\facade\Config;
use think\facade\Env;
use think\facade\Db;
use think\facade\Log;
use think\Response;

/**
 * @OA\Tag(
 *     name="微信",
 *     description="微信授权相关接口"
 * )
 */
class WechatController extends ApiBaseController
{
    /**
     * 微信公众号实例
     * @var \EasyWeChat\OfficialAccount\Application
     */
    protected $app;
    
    /**
     * 初始化
     */
    protected function initialize()
    {
        parent::initialize();
        
        // 初始化EasyWeChat配置
        $config = [
            'app_id' => Env::get('wechat.WECHAT_OFFICIAL_ACCOUNT_APPID', ''),
            'secret' => Env::get('wechat.WECHAT_OFFICIAL_ACCOUNT_SECRET', ''),
            'token' => Env::get('wechat.WECHAT_OFFICIAL_ACCOUNT_TOKEN', ''),
            'aes_key' => Env::get('wechat.WECHAT_OFFICIAL_ACCOUNT_AES_KEY', ''),
            
            'oauth' => [
                'scopes'   => explode(',', Env::get('wechat.WECHAT_OFFICIAL_ACCOUNT_OAUTH_SCOPES', 'snsapi_userinfo')),
                'callback' => Env::get('wechat.WECHAT_OFFICIAL_ACCOUNT_OAUTH_CALLBACK', ''),
            ],
        ];
        
        $this->app = Factory::officialAccount($config);
    }
    
    /**
     * @OA\Get(
     *     path="/api/wechat/oauth_url",
     *     summary="获取微信授权链接",
     *     tags={"微信"},
     *     @OA\Parameter(
     *         name="invite_code",
     *         in="query",
     *         description="邀请码",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="success"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="url", type="string", example="https://open.weixin.qq.com/...")
     *             )
     *         )
     *     )
     * )
     */
    public function oauthUrl()
    {
        // 获取邀请码
        $inviteCode = $this->request->param('invite_code', '');
        
        // 获取授权URL基础链接
        $url = $this->app->oauth->redirect()->getTargetUrl();
        // 如果有邀请码，在回调URL中添加邀请码参数
        if ($inviteCode) {
            // 获取配置中的回调URL
            $callbackUrl = Env::get('wechat.official_account_oauth_callback', '');
            
            // 添加邀请码参数
            $callbackUrlWithInviteCode = $callbackUrl;
            $callbackUrlWithInviteCode .= (strpos($callbackUrl, '?') !== false ? '&' : '?') . 'invite_code=' . $inviteCode;
            
            // 重新构建授权URL，替换回调URL
            $config = $this->app->getConfig();
            
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
            $query = [
                'appid' => $config['app_id'],
                'redirect_uri' => urlencode($callbackUrlWithInviteCode),
                'response_type' => 'code',
                'scope' => implode(',', $config['oauth']['scopes']),
                'state' => 'STATE',
            ];
            $url .= http_build_query($query) . '#wechat_redirect';
        }
        
        return $this->success(['url' => $url], '获取授权链接成功');
    }
    
    /**
     * @OA\Get(
     *     path="/api/wechat/oauth_callback",
     *     summary="微信授权回调",
     *     tags={"微信"},
     *     @OA\Parameter(
     *         name="code",
     *         in="query",
     *         description="微信授权码",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="msg", type="string", example="success"),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="token", type="string", example="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."),
     *                 @OA\Property(property="user", type="object",
     *                     @OA\Property(property="id", type="integer", example=1),
     *                     @OA\Property(property="nickname", type="string", example="张三"),
     *                     @OA\Property(property="avatar", type="string", example="http://example.com/avatar.jpg")
     *                 )
     *             )
     *         )
     *     )
     * )
     */
    public function oauthCallback()
    {
        try {
            // 获取授权用户信息
            $oauth = $this->app->oauth;
            $user = $oauth->user();
            $userInfo = $user->getOriginal();
            
            // 获取邀请码
            $inviteCode = $this->request->param('invite_code', '');
            
            // 处理用户信息，查找或创建用户
            $openid = $userInfo['openid'];
            $dbUser = User::where('openid', $openid)->find();
            
            // 开始事务
            Db::startTrans();
            
            try {
                $newUser = false;
                
                if (!$dbUser) {
                    // 创建新用户
                    $dbUser = User::create([
                        'openid' => $openid,
                        'nickname' => $userInfo['nickname'] ?? '',
                        'avatar' => $userInfo['headimgurl'] ?? '',
                        'gender' => $userInfo['sex'] ?? 0,
                        'city' => $userInfo['city'] ?? '',
                        'agent_level' => 1, // 默认为V1代理
                        'status' => 1,
                    ]);
                    $newUser = true;
                } else {
                    // 更新用户信息
                    $dbUser->save([
                        'nickname' => $userInfo['nickname'] ?? $dbUser->nickname,
                        'avatar' => $userInfo['headimgurl'] ?? $dbUser->avatar,
                        'gender' => $userInfo['sex'] ?? $dbUser->gender,
                        'city' => $userInfo['city'] ?? $dbUser->city,
                    ]);
                }
                
                // 如果有邀请码并且用户没有上级或者是新用户，尝试绑定上级
                if ($inviteCode && ($newUser || !$dbUser->parent_id)) {
                    $this->bindParent($dbUser, $inviteCode);
                }
                
                // 提交事务
                Db::commit();
                
                // 生成token
                $token = $this->createToken($dbUser);
                
                
                // 返回用户信息和Token到前端（前端需要接收并保存）
                $data = [
                    'user' => $dbUser,
                    'token' => 'Bearer ' . $token
                 ];
                
                return $this->success($data, '授权成功');
                // 重定向URL可以包含一些状态信息，如是否新用户、是否成功绑定等
                // $redirectParams = [];
                // if ($newUser) {
                //     $redirectParams[] = 'new_user=1';
                // }
                // if ($inviteCode) {
                //     $redirectParams[] = 'invite_from=' . $inviteCode;
                // }
                
                // $redirectUrl = '/';
                // if (!empty($redirectParams)) {
                //     $redirectUrl .= '?' . implode('&', $redirectParams);
                // }
                
                // // 这里返回HTML页面，包含脚本进行跳转
                // return '<html><script>window.localStorage.setItem("token", "' . $data['token'] . '"); window.location.href = "' . $redirectUrl . '";</script></html>';
                
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
        } catch (\Exception $e) {
            return $this->error('授权失败：' . $e->getMessage());
        }
    }
    
    /**
     * 创建登录Token
     *
     * @param User $user
     * @return string
     */
    protected function createToken(User $user)
    {
        // 创建简单的Token，实际项目中建议使用JWT
        $data = [
            'openid' => $user->openid,
            'id' => $user->id,
            'time' => time()
        ];
        
        return base64_encode(json_encode($data));
    }
    
    
    /**
     * 处理纸条抽取
     *
     * @param NoteDraw $noteDraw
     */
    protected function processNoteDraw($noteDraw)
    {
        if ($noteDraw->draw_type == 1) {
            // 单抽，标记纸条为已抽取
            $note = Note::find($noteDraw->note_id);
            if ($note) {
                $note->setDrawn();
            }
        } else {
            // 多抽，查找所有关联的纸条并标记为已抽取
            $noteItems = NoteDrawItem::where('draw_id', $noteDraw->id)->select();
            foreach ($noteItems as $item) {
                $note = Note::find($item->note_id);
                if ($note) {
                    $note->setDrawn();
                }
            }
        }
    }
    
    /**
     * 处理佣金分发
     *
     * @param NoteDraw $noteDraw
     */
    protected function processCommission($noteDraw)
    {
        // 获取抽取用户
        $drawUser = User::find($noteDraw->user_id);
        if (!$drawUser) {
            \think\facade\Log::error('处理佣金失败：抽取用户不存在。用户ID: ' . $noteDraw->user_id);
            return; // 用户不存在
        }
        
        \think\facade\Log::info('开始处理佣金，抽取用户ID: ' . $drawUser->id . '，订单金额: ' . $noteDraw->amount);
        
        // 获取抽取用户的上级链
        $parentChain = $this->getParentChain($drawUser->id);
        if (empty($parentChain)) {
            \think\facade\Log::info('用户无上级，不产生佣金。用户ID: ' . $drawUser->id);
            return; // 无上级用户
        }
        
        \think\facade\Log::info('发现上级链，长度: ' . count($parentChain));
        
        // 处理层级佣金
        foreach ($parentChain as $level => $parent) {
            // level从0开始，所以要+1才是真实层级
            $realLevel = $level + 1;
            $this->processLevelCommission($parent, $drawUser, $noteDraw, $realLevel);
        }
        
        // 处理同级推荐奖励
        $this->processSameLevelBonus($drawUser, $noteDraw, $parentChain);
    }
    
    /**
     * 获取用户的完整上级链（无限层级）
     *
     * @param int $userId 用户ID
     * @return array 上级用户数组，按层级排序（一级在前）
     */
    protected function getParentChain($userId)
    {
        $chain = [];
        $currentId = $userId;
        $maxLevels = 100; // 预防循环引用设置最大查询层级
        $processedIds = []; // 用于检测循环引用
        
        for ($i = 0; $i < $maxLevels; $i++) {
            $user = User::find($currentId);
            if (!$user || !$user->parent_id || $user->parent_id == 0) {
                break; // 无上级或已到顶级
            }
            
            // 检测循环引用
            if (in_array($user->parent_id, $processedIds)) {
                \think\facade\Log::warning('检测到上级链循环引用。用户ID: ' . $currentId . '，上级ID: ' . $user->parent_id);
                break;
            }
            
            $parent = User::find($user->parent_id);
            if (!$parent) {
                break; // 上级不存在
            }
            
            $chain[] = $parent; // 添加到链中
            $processedIds[] = $user->parent_id; // 记录处理过的ID
            $currentId = $user->parent_id; // 继续向上
        }
        
        return $chain;
    }
    
    /**
     * 处理层级佣金
     *
     * @param User $recipient 佣金接收用户
     * @param User $drawUser 抽取用户
     * @param NoteDraw $noteDraw 抽取订单
     * @param int $level 层级关系
     */
    protected function processLevelCommission($recipient, $drawUser, $noteDraw, $level)
    {
        $amount = $noteDraw->amount;
        $commissionRate = $this->calculateCommissionRate($recipient, $drawUser, $level);
        
        if ($commissionRate > 0) {
            $commissionAmount = $amount * $commissionRate;
            
            \think\facade\Log::info(
                '计算层级佣金：接收方ID=' . $recipient->id . 
                '，代理等级V' . $recipient->agent_level . 
                '，来源用户ID=' . $drawUser->id . 
                '，来源等级V' . $drawUser->agent_level . 
                '，层级=' . $level . 
                '，比例=' . ($commissionRate * 100) . '%' . 
                '，金额=' . $commissionAmount
            );
            
            // 创建佣金记录
            CommissionRecord::create([
                'user_id' => $recipient->id,
                'from_user_id' => $drawUser->id,
                'order_id' => $noteDraw->order_id,
                'amount' => $commissionAmount,
                'level' => $level,
                'from_level' => $drawUser->agent_level,
                'status' => 1,
                'remark' => '层级佣金 - ' . $level . '级'
            ]);
            
            // 更新用户佣金
            $recipient->commission += $commissionAmount;
            $recipient->save();
            
            // 更新团队佣金统计
            $this->updateTeamCommission($recipient, $drawUser, $commissionAmount, $level);
            
            // 检查并执行自动升级
            $recipient->checkAndAutoUpgrade();
        }
    }
    
    /**
     * 计算佣金比例
     *
     * @param User $recipient 佣金接收用户
     * @param User $drawUser 抽取用户
     * @param int $level 层级关系
     * @return float 佣金比例（小数形式，如0.54表示54%）
     */
    protected function calculateCommissionRate($recipient, $drawUser, $level)
    {
        $recipientLevel = $recipient->agent_level ?? 0;
        $drawUserLevel = $drawUser->agent_level ?? 0;
        
        // 获取系统设置中的佣金比例参数
        $settings = \app\model\SystemSetting::getSettings();
        
        // V1代理佣金规则
        if ($recipientLevel == 1) {
            // 直属一代充值：可获得佣金
            if ($level == 1) {
                return floatval($settings['v1_first_level_rate'] ?? 0.54);
            }
            // 二代及以后：无佣金
            return 0;
        }
        
        // V2代理佣金规则
        if ($recipientLevel == 2) {
            // 直属一代充值：可获得佣金
            if ($level == 1) {
                return floatval($settings['v2_first_level_rate'] ?? 0.65);
            }
            // 二级充值
            if ($level == 2) {
                return floatval($settings['v2_second_level_rate'] ?? 0.09);
            }
            // 三代及以后充值：可获得佣金（无限层级）
            return floatval($settings['v2_other_level_rate'] ?? 0.09);
        }
        
        // V3代理佣金规则
        if ($recipientLevel == 3) {
            // V1用户充值佣金
            if ($drawUserLevel == 1) {
                // 一代V1充值
                if ($level == 1) {
                    return floatval($settings['v3_v1_first_level_rate'] ?? 0.21);
                }
                // 二代及以后V1充值
                return floatval($settings['v3_v1_other_level_rate'] ?? 0.19);
            }
            
            // V2用户充值佣金或基础充值佣金
            return floatval($settings['v3_basic_rate'] ?? 0.10);
        }
        
        // 非代理，不获得佣金
        return 0;
    }
    
    /**
     * 处理同级推荐奖励
     *
     * @param User $drawUser 抽取用户
     * @param NoteDraw $noteDraw 抽取订单
     * @param array $parentChain 上级链
     */
    protected function processSameLevelBonus($drawUser, $noteDraw, $parentChain)
    {
        $amount = $noteDraw->amount;
        
        foreach ($parentChain as $level => $parent) {
            // 查找这个上级的推荐人（即再上一级）
            if (!isset($parentChain[$level + 1])) {
                continue; // 没有再上一级，跳过
            }
            
            $grandParent = $parentChain[$level + 1];
            
            // 如果上级和再上级的代理等级相同，可能触发同级推荐奖励
            if ($parent->agent_level == $grandParent->agent_level) {
                $bonusRate = $this->calculateSameLevelBonusRate($grandParent, $parent, $level + 1);
                
                if ($bonusRate > 0) {
                    $bonusAmount = $amount * $bonusRate;
                    
                    \think\facade\Log::info(
                        '计算同级推荐奖励：接收方ID=' . $grandParent->id . 
                        '，代理等级V' . $grandParent->agent_level . 
                        '，同级用户ID=' . $parent->id . 
                        '，团队层级=' . ($level + 2) . 
                        '，比例=' . ($bonusRate * 100) . '%' . 
                        '，金额=' . $bonusAmount
                    );
                    
                    // 创建佣金记录
                    CommissionRecord::create([
                        'user_id' => $grandParent->id,
                        'from_user_id' => $drawUser->id,
                        'order_id' => $noteDraw->order_id,
                        'amount' => $bonusAmount,
                        'level' => 0, // 特殊标记为同级奖励
                        'from_level' => $drawUser->agent_level,
                        'status' => 1,
                        'remark' => '同级推荐奖励 - V' . $parent->agent_level . '团队'
                    ]);
                    
                    // 更新用户佣金
                    $grandParent->commission += $bonusAmount;
                    $grandParent->save();
                    
                    // 检查并执行自动升级
                    $grandParent->checkAndAutoUpgrade();
                }
            }
        }
    }
    
    /**
     * 计算同级推荐奖励比例
     *
     * @param User $recipient 佣金接收用户（上级的上级）
     * @param User $sameLevelUser 同级用户（上级）
     * @param int $teamLevel 团队层级关系（这里与普通层级含义不同，指同级用户在接收用户下的第几代）
     * @return float 佣金比例
     */
    protected function calculateSameLevelBonusRate($recipient, $sameLevelUser, $teamLevel)
    {
        // 相同的代理等级
        $level = $recipient->agent_level;
        
        // 获取系统设置中的佣金比例参数
        $settings = \app\model\SystemSetting::getSettings();
        
        // V2同级推荐奖励
        if ($level == 2) {
            // 推荐V2用户，可获得该V2一代团队充值的佣金
            if ($teamLevel == 1) {
                return floatval($settings['v2_same_level_rate_1'] ?? 0.04);
            }
            // 如V2再推荐V2，可获得该V2三代团队充值的佣金
            if ($teamLevel == 2) {
                return floatval($settings['v2_same_level_rate_2'] ?? 0.02);
            }
        }
        
        // V3同级推荐奖励
        if ($level == 3) {
            // 同级一代团队充值
            if ($teamLevel == 1) {
                return floatval($settings['v3_same_level_rate_1'] ?? 0.02);
            }
            // 同级二代团队充值
            if ($teamLevel == 2) {
                return floatval($settings['v3_same_level_rate_2'] ?? 0.01);
            }
            // 同级三代及以后：无佣金
        }
        
        return 0;
    }
    
    /**
     * 更新团队佣金统计
     *
     * @param User $recipient 佣金接收用户
     * @param User $drawUser 抽取用户
     * @param float $commissionAmount 佣金金额
     * @param int $level 层级关系
     */
    protected function updateTeamCommission($recipient, $drawUser, $commissionAmount, $level)
    {
        // 如果是间接佣金（非一级关系），需要更新团队佣金
        if ($level > 1) {
            // 1. 更新直接上级的团队佣金
            $directParent = User::find($drawUser->parent_id);
            if ($directParent) {
                $directParent->team_commission += $commissionAmount;
                $directParent->save();
                
                \think\facade\Log::info('更新直接上级团队佣金：用户ID=' . $directParent->id . '，增加金额=' . $commissionAmount);
            }
            
            // 2. 获取抽取用户的最顶级父级，更新其团队佣金
            $topParentId = $drawUser->getTopParentId();
            if ($topParentId && $topParentId != $directParent->id) {
                $topParent = User::find($topParentId);
                if ($topParent) {
                    $topParent->team_commission += $commissionAmount;
                    $topParent->save();
                    
                    \think\facade\Log::info('更新顶级上级团队佣金：用户ID=' . $topParent->id . '，增加金额=' . $commissionAmount);
                }
            }
        }
    }
    
    /**
     * 绑定上级代理
     *
     * @param User $user 用户对象
     * @param string $inviteCode 邀请码(上级用户ID)
     * @return bool
     * @throws \Exception
     */
    protected function bindParent($user, $inviteCode)
    {
        // 如果已经有上级，不能再绑定
        if ($user->parent_id > 0) {
            return false;
        }
        
        // 查找要绑定的上级用户
        $parent = User::where('id', $inviteCode)->find();
        if (!$parent) {
            return false;
        }
        
        // 不能绑定自己
        if ($parent->id == $user->id) {
            return false;
        }
        
        // 不能绑定下级为自己的上级（防止循环）
        $tempId = $parent->parent_id;
        while ($tempId > 0) {
            if ($tempId == $user->id) {
                return false;
            }
            
            $tempUser = User::where('id', $tempId)->find();
            if (!$tempUser) {
                break;
            }
            
            $tempId = $tempUser->parent_id;
        }
        
        // 绑定上级
        $user->save([
            'parent_id' => $parent->id
        ]);
        
        // 更新上级的团队成员数量
        $parent->inc('team_count')->update();
        
        return true;
    }
    
    /**
     * @OA\Post(
     *     path="/api/wechat/payment/notify",
     *     summary="微信支付回调通知",
     *     tags={"微信"},
     *     description="接收微信支付结果的异步通知。不需要携带Token。",
     *     @OA\RequestBody(
     *         description="微信支付回调的XML数据",
     *         required=true,
     *         @OA\MediaType(
     *             mediaType="application/xml",
     *             @OA\Schema(type="string")
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="微信要求的成功或失败的XML响应",
     *         @OA\MediaType(
     *             mediaType="application/xml",
     *             @OA\Schema(type="string", example="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>")
     *         )
     *     )
     * )
     */
    public function paymentNotify()
    {
        // \think\facade\Log::info('=== 微信支付回调开始 ===');
        // \think\facade\Log::info('接收到微信支付回调数据：' . file_get_contents('php://input'));
        
        // 获取微信支付配置
        $config = [
            'app_id' => Env::get('wechat.WECHAT_PAYMENT_APPID', ''),
            'mch_id' => Env::get('wechat.WECHAT_PAYMENT_MCH_ID', ''),
            'key' => Env::get('wechat.WECHAT_PAYMENT_KEY', ''),
            'notify_url' => Env::get('wechat.WECHAT_PAYMENT_NOTIFY_URL', ''),
        ];
        
        // \think\facade\Log::info('微信支付配置信息：' . json_encode([
        //     'app_id' => $config['app_id'],
        //     'mch_id' => $config['mch_id'],
        //     'key_exists' => !empty($config['key']),
        //     'notify_url' => $config['notify_url'],
        // ], JSON_UNESCAPED_UNICODE));
        
        $payment = Factory::payment($config);
        
        try {
            $response = $payment->handlePaidNotify(function ($message, $fail) {
                // \think\facade\Log::info('处理微信支付回调数据：' . json_encode($message, JSON_UNESCAPED_UNICODE));
                
                try {
                    // 检查消息是否成功
                    if ($message['return_code'] !== 'SUCCESS') {
                        \think\facade\Log::error('通信失败：' . ($message['return_msg'] ?? '未知错误'));
                        return $fail('通信失败');
                    }
                    
                    // 获取我们的订单号
                    $out_trade_no = $message['out_trade_no'];
                    // \think\facade\Log::info('处理订单：' . $out_trade_no);
                    
                    // 查询订单
                    $noteDraw = NoteDraw::where('order_id', $out_trade_no)->find();
                    
                    if (!$noteDraw) {
                        // \think\facade\Log::error('订单不存在：' . $out_trade_no);
                        return $fail('订单不存在'); // 或者根据业务逻辑处理，可能需要记录日志
                    }
                    
                    \think\facade\Log::info('找到订单：' . $out_trade_no . '，当前状态：' . $noteDraw->status);
                    
                    // 如果订单状态已经是成功，直接返回true，表示无需重复处理
                    if ($noteDraw->status == 1) {
                        // \think\facade\Log::info('订单已处理，无需重复处理：' . $out_trade_no);
                        return true;
                    }
                    
                    // 验证业务结果
                    if ($message['result_code'] !== 'SUCCESS') {
                        // 可以记录支付失败的日志
                        // \think\facade\Log::error('支付失败：' . json_encode($message, JSON_UNESCAPED_UNICODE));
                        return $fail('支付失败'); // 通知微信支付失败
                    }
                    
                    // 验证订单金额 (微信单位为分)
                    $orderAmount = (int)($noteDraw->amount * 100);
                    $payAmount = (int)$message['total_fee'];
                    // \think\facade\Log::info('验证金额 - 订单金额：' . $orderAmount . '分，支付金额：' . $payAmount . '分');
                    
                    if ($payAmount !== $orderAmount) {
                        // \think\facade\Log::error('订单金额不符 - 订单金额：' . $orderAmount . '分，支付金额：' . $payAmount . '分');
                        return $fail('订单金额不符');
                    }
                    
                    // 启动数据库事务处理后续逻辑
                    // \think\facade\Log::info('开始事务处理');
                    Db::startTrans();
                    try {
                        // 更新订单状态为已支付
                        $noteDraw->save([
                            'status' => 1,
                            'pay_time' => date('Y-m-d H:i:s') // 记录支付时间
                        ]);
                        // \think\facade\Log::info('订单状态已更新为已支付');
                        
                        // 处理纸条抽取
                        // \think\facade\Log::info('开始处理纸条抽取');
                        $this->processNoteDraw($noteDraw);
                        // \think\facade\Log::info('纸条抽取处理完成');
                        
                        // 处理佣金分发
                        // \think\facade\Log::info('开始处理佣金分发');
                        $this->processCommission($noteDraw);
                        // \think\facade\Log::info('佣金分发处理完成');
                        
                        // 提交事务
                        Db::commit();
                        // \think\facade\Log::info('事务提交成功，订单处理完成：' . $out_trade_no);
                        
                        return true; // 返回 true 告诉微信已经成功处理了，不要再通知了
                        
                    } catch (\Exception $e) {
                        // 发生异常，回滚事务
                        Db::rollback();
                        // \think\facade\Log::error('处理异常：' . $e->getMessage() . ' | 跟踪信息：' . $e->getTraceAsString());
                        // 返回错误，微信会尝试再次通知
                        return $fail('系统处理失败: ' . $e->getMessage());
                    }
                } catch (\Exception $e) {
                    // \think\facade\Log::error('回调处理异常：' . $e->getMessage() . ' | 跟踪信息：' . $e->getTraceAsString());
                    return $fail('系统处理失败: ' . $e->getMessage());
                }
            });
            
            // \think\facade\Log::info('微信支付回调处理完成，返回响应');
            
            // 将 EasyWeChat 返回的响应实例返回给 ThinkPHP 框架处理，它会自动发送响应给微信
            return Response::create($response->getContent(), 'xml', $response->getStatusCode());
            
        } catch (\Exception $e) {
            // \think\facade\Log::error('微信支付回调处理异常：' . $e->getMessage() . ' | 跟踪信息：' . $e->getTraceAsString());
            // 如果发生异常，返回错误响应给微信
            return Response::create('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[系统异常：' . $e->getMessage() . ']]></return_msg></xml>', 'xml', 500);
        }
    }
} 